"""
颜色触发器设置对话框
允许用户配置检测方法、区域大小等参数
"""

from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QFormLayout, 
                               QLabel, QSpinBox, QComboBox, QDoubleSpinBox,
                               QPushButton, QGroupBox, QCheckBox, QSlider,
                               QTabWidget, QWidget, QTextEdit, QMessageBox)
from PySide6.QtCore import Qt, Signal
import pyautogui

class ColorTriggerSettingsDialog(QDialog):
    """颜色触发器设置对话框"""
    
    def __init__(self, trigger_item, parent=None):
        super().__init__(parent)
        self.trigger_item = trigger_item
        self.setWindowTitle(f"设置 - {trigger_item.name}")
        self.setModal(True)
        self.resize(500, 600)
        
        self.setup_ui()
        self.load_settings()
    
    def setup_ui(self):
        """设置UI界面"""
        layout = QVBoxLayout(self)
        
        # 创建选项卡
        tab_widget = QTabWidget()
        layout.addWidget(tab_widget)
        
        # 检测方法选项卡
        detection_tab = QWidget()
        tab_widget.addTab(detection_tab, "检测方法")
        self.setup_detection_tab(detection_tab)
        
        # 区域设置选项卡
        region_tab = QWidget()
        tab_widget.addTab(region_tab, "检测区域")
        self.setup_region_tab(region_tab)
        
        # 高级设置选项卡
        advanced_tab = QWidget()
        tab_widget.addTab(advanced_tab, "高级设置")
        self.setup_advanced_tab(advanced_tab)
        
        # 按钮区域
        button_layout = QHBoxLayout()
        
        # 预览按钮
        self.preview_btn = QPushButton("预览检测区域")
        self.preview_btn.clicked.connect(self.preview_detection_area)
        button_layout.addWidget(self.preview_btn)
        
        button_layout.addStretch()
        
        # 确定和取消按钮
        self.ok_btn = QPushButton("确定")
        self.ok_btn.clicked.connect(self.accept)
        button_layout.addWidget(self.ok_btn)
        
        self.cancel_btn = QPushButton("取消")
        self.cancel_btn.clicked.connect(self.reject)
        button_layout.addWidget(self.cancel_btn)
        
        layout.addLayout(button_layout)
    
    def setup_detection_tab(self, tab):
        """设置检测方法选项卡"""
        layout = QVBoxLayout(tab)
        
        # 检测方法选择
        method_group = QGroupBox("检测方法")
        method_layout = QFormLayout(method_group)
        
        self.detection_method_combo = QComboBox()
        self.detection_method_combo.addItems([
            "traditional", "kmeans", "hybrid", "dominant_kmeans"
        ])
        self.detection_method_combo.setCurrentText(self.trigger_item.detection_method)
        self.detection_method_combo.currentTextChanged.connect(self.on_detection_method_changed)
        method_layout.addRow("检测方法:", self.detection_method_combo)
        
        # 方法说明
        self.method_description = QTextEdit()
        self.method_description.setMaximumHeight(100)
        self.method_description.setReadOnly(True)
        method_layout.addRow("说明:", self.method_description)
        
        layout.addWidget(method_group)
        
        # K-Means设置
        self.kmeans_group = QGroupBox("K-Means设置")
        kmeans_layout = QFormLayout(self.kmeans_group)
        
        self.kmeans_clusters_spin = QSpinBox()
        self.kmeans_clusters_spin.setRange(2, 8)
        self.kmeans_clusters_spin.setValue(self.trigger_item.kmeans_clusters)
        kmeans_layout.addRow("聚类数量:", self.kmeans_clusters_spin)
        
        self.confidence_threshold_spin = QDoubleSpinBox()
        self.confidence_threshold_spin.setRange(0.1, 1.0)
        self.confidence_threshold_spin.setSingleStep(0.1)
        self.confidence_threshold_spin.setValue(self.trigger_item.confidence_threshold)
        kmeans_layout.addRow("置信度阈值:", self.confidence_threshold_spin)
        
        layout.addWidget(self.kmeans_group)
        
        layout.addStretch()
        
        # 更新方法说明
        self.on_detection_method_changed()
    
    def setup_region_tab(self, tab):
        """设置检测区域选项卡"""
        layout = QVBoxLayout(tab)
        
        # 屏幕信息
        screen_width, screen_height = pyautogui.size()
        screen_info = QLabel(f"屏幕尺寸: {screen_width} x {screen_height} 像素")
        screen_info.setStyleSheet("color: gray; font-size: 10px;")
        layout.addWidget(screen_info)
        
        # 主要颜色检测区域设置
        self.dominant_region_group = QGroupBox("主要颜色检测区域")
        dominant_layout = QFormLayout(self.dominant_region_group)
        
        # 区域大小
        self.region_size_spin = QSpinBox()
        self.region_size_spin.setRange(50, 500)
        self.region_size_spin.setSingleStep(10)
        self.region_size_spin.setValue(getattr(self.trigger_item, 'dominant_region_size', 200))
        self.region_size_spin.valueChanged.connect(self.update_region_info)
        dominant_layout.addRow("区域大小 (像素):", self.region_size_spin)
        
        # 快速设置按钮
        size_buttons_layout = QHBoxLayout()
        for size in [100, 150, 200, 250, 300]:
            btn = QPushButton(f"{size}")
            btn.clicked.connect(lambda checked, s=size: self.region_size_spin.setValue(s))
            size_buttons_layout.addWidget(btn)
        dominant_layout.addRow("快速设置:", size_buttons_layout)
        
        # 中心偏移
        self.offset_x_spin = QSpinBox()
        self.offset_x_spin.setRange(-500, 500)
        self.offset_x_spin.setValue(getattr(self.trigger_item, 'dominant_center_offset_x', 0))
        dominant_layout.addRow("X偏移 (像素):", self.offset_x_spin)
        
        self.offset_y_spin = QSpinBox()
        self.offset_y_spin.setRange(-500, 500)
        self.offset_y_spin.setValue(getattr(self.trigger_item, 'dominant_center_offset_y', 0))
        dominant_layout.addRow("Y偏移 (像素):", self.offset_y_spin)
        
        # 区域信息显示
        self.region_info_label = QLabel()
        self.region_info_label.setStyleSheet("color: blue; font-size: 10px;")
        dominant_layout.addRow("区域信息:", self.region_info_label)
        
        layout.addWidget(self.dominant_region_group)
        
        # 传统方法区域设置
        traditional_group = QGroupBox("传统方法检测区域")
        traditional_layout = QFormLayout(traditional_group)
        
        self.traditional_width_spin = QSpinBox()
        self.traditional_width_spin.setRange(5, 100)
        self.traditional_width_spin.setValue(self.trigger_item.detection_area_width)
        traditional_layout.addRow("宽度 (像素):", self.traditional_width_spin)
        
        self.traditional_height_spin = QSpinBox()
        self.traditional_height_spin.setRange(5, 100)
        self.traditional_height_spin.setValue(self.trigger_item.detection_area_height)
        traditional_layout.addRow("高度 (像素):", self.traditional_height_spin)
        
        layout.addWidget(traditional_group)
        
        layout.addStretch()
        
        # 更新区域信息
        self.update_region_info()
    
    def setup_advanced_tab(self, tab):
        """设置高级设置选项卡"""
        layout = QVBoxLayout(tab)
        
        # 性能设置
        performance_group = QGroupBox("性能设置")
        performance_layout = QFormLayout(performance_group)
        
        # 缓存设置
        self.cache_duration_spin = QDoubleSpinBox()
        self.cache_duration_spin.setRange(0.001, 1.0)
        self.cache_duration_spin.setSingleStep(0.01)
        self.cache_duration_spin.setDecimals(3)
        self.cache_duration_spin.setValue(0.01)
        performance_layout.addRow("缓存时间 (秒):", self.cache_duration_spin)
        
        layout.addWidget(performance_group)
        
        # 游戏优化设置
        game_group = QGroupBox("游戏场景优化")
        game_layout = QFormLayout(game_group)
        
        # 预设配置
        preset_layout = QHBoxLayout()
        fps_btn = QPushButton("FPS游戏")
        fps_btn.clicked.connect(lambda: self.apply_preset("fps"))
        moba_btn = QPushButton("MOBA游戏")
        moba_btn.clicked.connect(lambda: self.apply_preset("moba"))
        rpg_btn = QPushButton("RPG游戏")
        rpg_btn.clicked.connect(lambda: self.apply_preset("rpg"))
        
        preset_layout.addWidget(fps_btn)
        preset_layout.addWidget(moba_btn)
        preset_layout.addWidget(rpg_btn)
        game_layout.addRow("预设配置:", preset_layout)
        
        layout.addWidget(game_group)
        
        layout.addStretch()
    
    def on_detection_method_changed(self):
        """检测方法改变时的处理"""
        method = self.detection_method_combo.currentText()
        
        descriptions = {
            "traditional": "传统方法：计算检测区域内像素的平均颜色。速度快，适合纯色区域。",
            "kmeans": "K-Means聚类：使用机器学习提取主要颜色。抗噪声强，适合复杂背景。",
            "hybrid": "混合方法：根据区域大小自动选择最适合的检测方法。",
            "dominant_kmeans": "主要颜色K-Means：专门提取屏幕中心区域的主要颜色，最适合游戏应用。"
        }
        
        self.method_description.setText(descriptions.get(method, ""))
        
        # 根据方法显示/隐藏相关设置
        is_kmeans_method = method in ["kmeans", "hybrid", "dominant_kmeans"]
        self.kmeans_group.setVisible(is_kmeans_method)
        
        is_dominant_method = method == "dominant_kmeans"
        self.dominant_region_group.setVisible(is_dominant_method)
    
    def update_region_info(self):
        """更新区域信息显示"""
        try:
            screen_width, screen_height = pyautogui.size()
            center_x, center_y = screen_width // 2, screen_height // 2
            
            region_size = self.region_size_spin.value()
            offset_x = self.offset_x_spin.value()
            offset_y = self.offset_y_spin.value()
            
            # 计算实际检测中心
            actual_center_x = center_x + offset_x
            actual_center_y = center_y + offset_y
            
            # 计算区域边界
            half_size = region_size // 2
            left = actual_center_x - half_size
            top = actual_center_y - half_size
            right = actual_center_x + half_size
            bottom = actual_center_y + half_size
            
            # 检查边界
            in_bounds = (left >= 0 and top >= 0 and 
                        right <= screen_width and bottom <= screen_height)
            
            pixel_count = region_size * region_size
            
            info_text = f"中心: ({actual_center_x}, {actual_center_y})\n"
            info_text += f"范围: ({left}, {top}) 到 ({right}, {bottom})\n"
            info_text += f"像素数: {pixel_count:,} 个\n"
            info_text += f"边界检查: {'✅ 正常' if in_bounds else '❌ 超出屏幕'}"
            
            self.region_info_label.setText(info_text)
            
        except Exception as e:
            self.region_info_label.setText(f"计算错误: {e}")
    
    def apply_preset(self, preset_type):
        """应用预设配置"""
        presets = {
            "fps": {
                "detection_method": "dominant_kmeans",
                "region_size": 200,
                "clusters": 3,
                "confidence": 0.4,
                "description": "FPS游戏优化：中等区域，平衡精度和性能"
            },
            "moba": {
                "detection_method": "dominant_kmeans", 
                "region_size": 120,
                "clusters": 2,
                "confidence": 0.3,
                "description": "MOBA游戏优化：小区域，精确UI检测"
            },
            "rpg": {
                "detection_method": "dominant_kmeans",
                "region_size": 150,
                "clusters": 3,
                "confidence": 0.35,
                "description": "RPG游戏优化：适中区域，物品检测"
            }
        }
        
        if preset_type in presets:
            preset = presets[preset_type]
            
            self.detection_method_combo.setCurrentText(preset["detection_method"])
            self.region_size_spin.setValue(preset["region_size"])
            self.kmeans_clusters_spin.setValue(preset["clusters"])
            self.confidence_threshold_spin.setValue(preset["confidence"])
            
            QMessageBox.information(self, "预设应用", 
                                  f"已应用{preset_type.upper()}游戏预设配置\n\n{preset['description']}")
    
    def preview_detection_area(self):
        """预览检测区域"""
        try:
            # 导入可视化工具
            import subprocess
            import sys
            
            # 创建临时预览脚本
            preview_script = f"""
import tkinter as tk
import pyautogui

# 获取当前设置
region_size = {self.region_size_spin.value()}
offset_x = {self.offset_x_spin.value()}
offset_y = {self.offset_y_spin.value()}

# 计算位置
screen_width, screen_height = pyautogui.size()
center_x, center_y = screen_width // 2, screen_height // 2
actual_center_x = center_x + offset_x
actual_center_y = center_y + offset_y
half_size = region_size // 2
left = actual_center_x - half_size
top = actual_center_y - half_size

# 创建预览窗口
root = tk.Toplevel()
root.title("检测区域预览")
root.geometry(f"{{region_size}}x{{region_size}}+{{left}}+{{top}}")
root.attributes('-topmost', True)
root.attributes('-alpha', 0.4)
root.configure(bg='red')

# 添加标签
label = tk.Label(root, text=f"检测区域\\n{{region_size}}x{{region_size}}", 
               bg='red', fg='white', font=("Arial", 12, "bold"))
label.pack(expand=True)

# 3秒后关闭
root.after(3000, root.destroy)
"""
            
            # 显示预览信息
            QMessageBox.information(self, "预览检测区域", 
                                  f"将在屏幕上显示红色半透明区域\n\n"
                                  f"区域大小: {self.region_size_spin.value()}x{self.region_size_spin.value()}\n"
                                  f"偏移: ({self.offset_x_spin.value()}, {self.offset_y_spin.value()})\n"
                                  f"显示时间: 3秒")
            
            # 执行预览（简化版本）
            exec(preview_script)
            
        except Exception as e:
            QMessageBox.warning(self, "预览失败", f"无法显示预览: {e}")
    
    def load_settings(self):
        """加载当前设置"""
        # 检测方法相关设置已在UI创建时设置
        pass
    
    def accept(self):
        """确定按钮处理"""
        try:
            # 保存设置到触发器
            self.trigger_item.detection_method = self.detection_method_combo.currentText()
            self.trigger_item.kmeans_clusters = self.kmeans_clusters_spin.value()
            self.trigger_item.confidence_threshold = self.confidence_threshold_spin.value()
            
            # 主要颜色检测设置
            self.trigger_item.dominant_region_size = self.region_size_spin.value()
            self.trigger_item.dominant_center_offset_x = self.offset_x_spin.value()
            self.trigger_item.dominant_center_offset_y = self.offset_y_spin.value()
            
            # 传统方法设置
            self.trigger_item.detection_area_width = self.traditional_width_spin.value()
            self.trigger_item.detection_area_height = self.traditional_height_spin.value()
            
            super().accept()
            
        except Exception as e:
            QMessageBox.warning(self, "保存失败", f"保存设置时出错: {e}")
